#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <signal.h>
#include <unistd.h>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <ctype.h>
#include "log.hpp"

class Sock
{
private:
    const static int backlog = 20;
public:
    Sock(){}
    
    int Socket()
    {
        int _listenSock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listenSock < 0)
        {
            logMessage(FATAL, "create socket error %d:%s", errno, strerror(errno));
            exit(1);
        }
        logMessage(NORMAL, "create socket success, listensock: %d", _listenSock); // 3

        return _listenSock;
    }

    void Bind(int sock, uint16_t port, std::string ip = "0.0.0.0")
    {
        struct sockaddr_in local;
        bzero(&local, 0);
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &local.sin_addr);
        // local.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());

        if (bind(sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind error %d:%s", errno, strerror(errno));
            exit(1);
        }
    }

    void Listen(int sock)
    {
        if (listen(sock, backlog) < 0)
        {
            logMessage(FATAL, "listen error %d:%s", errno, strerror(errno));
            exit(1);
        }
        logMessage(NORMAL, "init server success");
    }

    int Accept(int sock, std::string *ip, uint16_t *port)
    {
        struct sockaddr_in src;
        socklen_t len = sizeof(src);
        int serSocket = accept(sock, (struct sockaddr *)&src, &len);
        if (serSocket < 0)
        {
            logMessage(ERROR, "accept error %d:%s", errno, strerror(errno));
            return -1;
        }

        if(port) *port = ntohs(src.sin_port);
        if(ip) *ip = inet_ntoa(src.sin_addr);

        return serSocket;
    }

    bool Connect(int sock,const std::string& server_ip,const uint16_t& server_port)
    {
        struct sockaddr_in server;
        bzero(&server,0);
        server.sin_family = AF_INET;
        server.sin_port = htons(server_port);
        server.sin_addr.s_addr = inet_addr(server_ip.c_str());

        if(connect(sock,(struct sockaddr*)&server,sizeof(server)) == 0) return true;
        else return false;
    }

    ~Sock()
    {
    }
};
